package com.example.camera;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;

import android.app.ActionBar.LayoutParams;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.widget.FrameLayout;

public class CameraActivity extends VActivity {

	private Camera mCamera;
	private CameraPreview mPreview;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_camera_preview);

		Log.i(TAG, "Trying to load OpenCV library");
		if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_2, this,
				mOpenCVCallBack)) {
			Log.e(TAG, "Cannot connect to OpenCV Manager");
		}
		
		// Create an instance of Camera
		mCamera = getCameraInstance();
		
		// Create our Preview view and set it as the content of our activity
		mPreview = new CameraPreview(this, mCamera);
		FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
		preview.addView(mPreview);
		
		OpenCVPreview ocvPreview = (OpenCVPreview) findViewById(R.id.opencv_preview);
		mPreview.setHandler(ocvPreview.getCalculateHandler());
	}

	public static Camera getCameraInstance() {
		Camera c = null;
		
		try
		{
			c = Camera.open();
		}
		catch (Exception e)
		{
			Log.e(TAG, "Error: getCameraInstance() ", e);
		}
		
		return c;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) {
		@Override
		public void onManagerConnected(int status) {
			switch (status) {
			case LoaderCallbackInterface.SUCCESS: {
				Log.i(TAG, "OpenCV loaded successfully");
				// Create and set View
			}
				break;
			case LoaderCallbackInterface.INIT_FAILED: {
				Log.i(TAG, "OpenCV loading failed");
			}
				break;
			default: {
				super.onManagerConnected(status);
			}
				break;
			}
		}
	};
	
	@Override
	protected void onPause() {
		super.onPause();
		
		// Release the Camera because we don't need it when paused
		// and other activities might need to use it
		if (mCamera != null)
		{
			mCamera.release();
			mCamera = null;
		}
		
	};
	
	@Override
	protected void onResume() {
		super.onResume();
		mCamera = getCameraInstance();
	}

}
